package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.Accept;
import com.ruoyi.system.domain.Share;
import com.ruoyi.system.domain.bo.ShareBo;
import com.ruoyi.system.domain.vo.ShareVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IShareService;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.io.ResolverUtil;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.FileBo;
import com.ruoyi.system.domain.vo.FileVo;
import com.ruoyi.system.domain.File;
import com.ruoyi.system.service.IFileService;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 分享Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-02
 */
@RequiredArgsConstructor
@Service
public class FileServiceImpl implements IFileService {

    private final FileMapper baseMapper;
    @Resource
    private final ISysConfigService iSysConfigService;
    private final AcceptMapper acceptMapper;
    @Resource
    private final IShareService iShareService;
    private final SysOssMapper sysOssMapper;


    /**
     * 查询分享
     */
    @Override
    public FileVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询分享列表
     */
    @Override
    public TableDataInfo<FileVo> queryPageList(FileBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<File> lqw = buildQueryWrapper(bo);
        Page<FileVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(x -> {
            x.setOss(sysOssMapper.selectVoById(x.getPath()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询分享列表
     */
    @Override
    public List<FileVo> queryList(FileBo bo) {
        LambdaQueryWrapper<File> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<File> buildQueryWrapper(FileBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<File> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getPath()), File::getPath, bo.getPath());
        lqw.eq(bo.getShareId() != null, File::getShareId, bo.getShareId());
        return lqw;
    }

    /**
     * 新增分享
     */
    @Override
    public Boolean insertByBo(FileBo bo) {
        File add = BeanUtil.toBean(bo, File.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改分享
     */
    @Override
    public Boolean updateByBo(FileBo bo) {
        File update = BeanUtil.toBean(bo, File.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(File entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除分享
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<FileVo> getListByCode(Long code, Long userId) {
        Share share = iShareService.queryByCode(code);
        if (share == null) {
            return new LinkedList<>();
        }
        Long expirationTime = share.getExp();
        LocalDateTime localDateTime = LocalDateTime.now().minusDays(expirationTime);
        LocalDateTime shareDateTime = LocalDateTimeUtil.of(share.getCreateTime());
        if (shareDateTime.isAfter(localDateTime)) {
            FileBo fileBo = new FileBo();
            fileBo.setShareId(share.getId());
            List<FileVo> result = this.queryList(fileBo);
            Accept accept = new Accept();
            accept.setUserId(userId);
            accept.setShareId(share.getId());
            acceptMapper.insert(accept);
            //拿到oss的详细信息
            result.forEach(x -> {
                x.setOss(sysOssMapper.selectVoById(x.getPath()));
            });


            return result;
        }
        return new LinkedList<>();
    }
}
